package com.cskaoyan.market.service.impl;

import com.cskaoyan.market.db.domain.MarketAd;
import com.cskaoyan.market.db.domain.MarketAdExample;
import com.cskaoyan.market.db.mapper.MarketAdMapper;
import com.cskaoyan.market.service.AdminAdService;
import com.cskaoyan.market.util.MybatisUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class AdminAdServiceImpl implements AdminAdService {
    @Override
    public List<MarketAd> list(String page, String limit, String sort, String order, String name, String content) {
        SqlSession session= MybatisUtil.getSession();
        MarketAdMapper adMapper = session.getMapper(MarketAdMapper.class);
        MarketAdExample marketAdExample = new MarketAdExample();
        MarketAdExample.Criteria criteria = marketAdExample.createCriteria();
        if(!StringUtils.isEmpty(name)){
            // select * from sxxx where username like '%xxx%'
            criteria.andNameLike("%" + name + "%");
        }
        if(!StringUtils.isEmpty(content)){
            criteria.andContentLike("%" + content + "%");
        }
        page="1";
        limit="20";
        marketAdExample.setOrderByClause(sort+" "+order);
        PageHelper.startPage(Integer.parseInt(page),Integer.parseInt(limit));
        List<MarketAd> marketAds = adMapper.selectByExample(marketAdExample);
        session.commit();
        session.close();
        return marketAds;
    }

    @Override
    public int delete(Integer id) {
        SqlSession session= MybatisUtil.getSession();
        MarketAdMapper adMapper = session.getMapper(MarketAdMapper.class);

        int i = adMapper.deleteByPrimaryKey(id);
        session.commit();
        session.close();
        return i;
    }

    @Override
    public int update(MarketAd marketAd) {
        SqlSession session= MybatisUtil.getSession();
        MarketAdMapper adMapper = session.getMapper(MarketAdMapper.class);
        int i = adMapper.updateByPrimaryKey(marketAd);
        session.commit();
        session.close();
        return i;
    }

    @Override
    public int create(MarketAd marketAd) {
        SqlSession session= MybatisUtil.getSession();
        MarketAdMapper adMapper = session.getMapper(MarketAdMapper.class);

        int i = adMapper.insert(marketAd);

        session.commit();
        session.close();
        return i;
    }


}
